const log = require('../../util/log')
const config = require('../../util/config')
const chromeMng = require('../chromeMng.20180824')
const ocrMng = require('../ocrMng')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = chromeMng.client;

async function getTaobaoAdvLink(obj) {
  obj = obj || {}
  obj.times = (obj.times || 0) + 1
  if (!obj.link) {
    return new Promise((resolve, reject) => {
      reject('缺少link')
    })
  }
  log('getting taobao advertising link')
  return new Promise((resolve, reject) => {
    chromeMng.loginTaobao().then(result => {
      step2(obj).then(result => {
        chromeMng.code = ''
        chromeMng.codeRequestId = 0
        chromeMng.codeText = ''
        resolve(result)
      }, result => {
        chromeMng.code = ''
        chromeMng.codeRequestId = 0
        chromeMng.codeText = ''
        reject(result)
      })
    }, result => {
      reject(result)
    })
  })
}

async function step2(obj) {
  obj.times++
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('系统错误')
    })
  }
  log('getting taobao advertising link step 2')
  var {result} = await Runtime.evaluate({expression: 'location.href'})
  if (result.value == 'https://pub.alimama.com/myunion.htm#!/promo/self/links') {
    return step3(obj)
  }
  Page.navigate({
    url: 'https://pub.alimama.com/myunion.htm#!/promo/self/links'
  })
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      step2(obj).then(result => {
        resolve(result)
      }, result => {
        reject(result)
      })
    }, 1000)
  })
}

async function step3(obj) {
  obj.times++
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('超时')
    })
  }
  log('getting taobao advertising link step 3')
  var {result} = await Runtime.evaluate({expression: 'location.href'})
  if (result.value != 'https://pub.alimama.com/myunion.htm#!/promo/self/links') {
    return step2(obj)
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#J_originUrl")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 0) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step3(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-overlay")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 1) {
    return step4(obj)
  }
  await Runtime.evaluate({expression: 'document.querySelectorAll("#J_originUrl")[0].value="' + obj.link + '"'})
  await Runtime.evaluate({expression: 'document.querySelectorAll("#J_vf_promo button")[0].click()'})
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      step3(obj).then(result => {
        resolve(result)
      }, result => {
        reject(result)
      })
    }, 1000)
  })
}

async function step4(obj) {
  try {
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting taobao advertising link step 4')
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-overlay")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return step3(obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("div.ux-tip.uxGlobalTip")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
      return new Promise((resolve, reject) => {
        reject('该商品不能返利')
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".getcode-box textarea")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt != 0) {
      var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".getcode-box textarea")[0].value'})
      return new Promise(resolve => {
        resolve(result.value)
        // Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-ext-close")[0].click()'})
      })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {//要输验证码
      var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")'})
      var cnt = result.description.substring(9, result.description.length - 1)
      if (cnt == 1) {
        // if (!ocrMng.aipOcr) {
        //   return new Promise((resolve, reject) => {
        //     reject('没有aipOcr可用了')
        //   })
        // }
        // var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#checkcode-state")[0].className'})
        // if (result.value.indexOf('checkcode-state-right') != -1) {
        //   await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
        // }
        // //换验证码
        // // await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")[0].click()'})
        // return new Promise((resolve, reject) => {
        //   setTimeout(() => {
        //     step4(obj).then(result => {
        //       resolve(result)
        //     }, result => {
        //       reject(result)
        //     })
        //   }, 2000)
        // })
        if (chromeMng.codeText) {
          await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CodeInput")[0].value="' + chromeMng.codeText + '"'})
          await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
          chromeMng.codeText = ''
        }
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step4(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-overlay button")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step4(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-overlay button")[0].click()'})
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step4(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getTaobaoAdvLink
